package com.situ.mp.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.situ.mp.pojo.User;
import com.situ.mp.pojo.query.UserQuery;
import com.situ.mp.service.IUserService;
import com.situ.mp.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.HashMap;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author Gao
 * @since 2024-07-13
 */
@RestController
@RequestMapping("/user")
//@CrossOrigin
public class UserController {
    @Autowired
    private IUserService userService;

    //@RequestMapping(value = "/list", method = RequestMethod.GET)
    @GetMapping("/list")
    public Result list(UserQuery userQuery) {
        IPage<User> iPage = new Page<>(userQuery.getPage(), userQuery.getLimit());
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.like(userQuery.getName() != null, "name", userQuery.getName());
        queryWrapper.eq(userQuery.getAge() != null, "age", userQuery.getAge());
        userService.page(iPage, queryWrapper);
        HashMap<String, Object> map = new HashMap<>();
        map.put("total", iPage.getTotal());
        map.put("list", iPage.getRecords());
        return Result.ok(map);
    }

    // /deleteById?id=12
    // /deleteById/12
    @DeleteMapping("/deleteById/{id}")
    public Result deleteById(@PathVariable Long id) {
        userService.removeById(id);
        return Result.ok("删除成功");
    }

    // /deleteAll/1,2,3
    @DeleteMapping("/deleteAll/{ids}")
    public Result deleteAll(@PathVariable Long[] ids) {
        userService.removeByIds(Arrays.asList(ids));
        return Result.ok("删除成功");
    }

    // @RequestBody  @ResponseBody
    @PostMapping("/add")
    public Result add(@RequestBody User user) {
        userService.saveOrUpdate(user);
        return Result.ok("成功");
    }

    // /selectById?id=23
    @GetMapping("/selectById")
    public Result selectById(Long id) {
        User user = userService.getById(id);
        return Result.ok(user);
    }

    @PutMapping("/update")
    public Result update(@RequestBody User user) {
        userService.saveOrUpdate(user);
        return Result.ok("成功");
    }

}

